<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/26
 * Time: 18:02
 */
namespace App\Http\Controllers\web;

use App\Models\V1\MessageModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntMemberInfo;
use App\Module\EntMobileCode;
use App\Module\EntBookRenewLog;
use App\Module\EntMemberDRP;
use App\Module\EntPushMoneyLog;
use App\Module\EntReturnMsg;
use App\Module\EntOrderPrepaidLog;
use Session;
use Redirect, Validator, Cookie, Response, DB, View;
use App\Common\MobileMassege;


class LoginController extends Controller
{
    protected $scaleOne = '0.3';
    protected $scaleTwo = '0.05';
    protected $scaleMoney = '2000';

    /*
     * 用户注册界面
     * */
    public function checkUser()
    {
        $MOpenid = Session::get('OPENID');
        return view('web/login/login', ['OPENID' => $MOpenid]);
    }


    /*
     * 会员登录
     * @param id 二维码扫描过来的父ID
     * */
    public function login($id=0,Request $request){

        /*1.判断是不是微信登录*/
        if(is_weixin()){
            //获取微信ID
            $code = $request->get('code');

            //code为空，获取code
            if(empty($code)){


                //如果没有用户信息，也没有code 获得code
                if(empty($code)){
                    //触发微信返回code码
                    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$currentUrl."&response_type=code&scope=snsapi_userinfo&state=ogreen#wechat_redirect";
                    Header("Location: $url");
                    exit();
                }
            }
        }
    }

    /*
     * 添加会员
     */
    public function loginstore(Request $request)
    {
        $MOpenid = Session::get('OPENID');
        if ($MOpenid == '') {
            return redirect::back()->withInput()->withErrors('获取用户信息失败，请稍后再试！');
        }

        /**用微信ID判断用户是否注册**/
        $memberInfo = $this->checkMemberInfo(2, $MOpenid);
        $loginKey = md5(date('YmdHis', time()));

        if (count($memberInfo) > 0) {       //存在该微信用户
            Session::put('MName', $memberInfo->UserName);
            Session::put('MKey', $loginKey);
            EntMemberInfo::where('MemNumber', $memberInfo->MemNumber)->update(['LoginKey' => $loginKey]);
            if ($memberInfo->States == 0) { //未付费会员
                return redirect('/pay/pay.html');
            } else {                        //付费会员
                return redirect('/book.html');
            }
        }

        /**电话号码   判断用户是否注册**/
        $userName       = trim($request->get('txtMobile'));
        $memberInfoTwo  = $this->checkMemberInfo(1, $userName);
        if (count($memberInfoTwo) > 0) {
            $data = ['LoginKey' => $loginKey];
            if($MOpenid){
                $data['WeiXID'] = $MOpenid;
            }
            Session::put('MName', $memberInfoTwo->UserName);
            Session::put('MKey', $loginKey);
            EntMemberInfo::where('MemNumber', $memberInfoTwo->MemNumber)
                ->update($data);
            if($memberInfoTwo->States == 1){
                return redirect('/book.html');//ron临时添加
            }else{
                return redirect('/pay/pay.html');
            }
        } else {
            $MemNumber = create_member_number();
            $userName = trim($request->get('txtMobile'));
            $entMemberInfo = new EntMemberInfo();
            $entMemberInfo->States      = 0;
            $entMemberInfo->MemNumber   = $MemNumber;
            $entMemberInfo->UserName    = $userName;
            $entMemberInfo->YourName    = trim($request->get('txtYourName'));
            $entMemberInfo->UserPassWord= '';
            $entMemberInfo->NickName    = '';
            $entMemberInfo->FilePath1   = '';
            $entMemberInfo->WeiXID      = $MOpenid;
            $entMemberInfo->VipNumber   = 1;
            $entMemberInfo->MemIntegral = 0;
            $entMemberInfo->LoginKey    = $loginKey;
            $entMemberInfo->MemEndTime  = '';
            $entMemberInfo->RegisterType = 2;
            $entMemberInfo->DeleteMark  = 1;
            $entMemberInfo->ReleaseDate = date('Y-m-d H:i:s', time());
            $entMemberInfo->AddDate     = date('Y-m-d H:i:s', time());
            $entMemberInfo->save();
            if (!$entMemberInfo) {
                return redirect::back()->withInput()->withErrors('会员注册失败，请稍后再试！');
            }

            Session::put('MName', $userName);
            Session::put('MKey', $loginKey);
            $DRPID = Session::get('DRPID');
            if ($DRPID != '' && $DRPID != '1') {
                $ParentID = $DRPID;
                $entMemberDRP = new EntMemberDRP();
                $entMemberDRP->MemNumber = $entMemberInfo->MemNumber;
                $entMemberDRP->SalesMoney = 0;
                $entMemberDRP->MemBalances = 0;
                $entMemberDRP->FinishMoney = 0;
                $entMemberDRP->DRPScale = '';
                $entMemberDRP->DRPLevel = 2;
                $entMemberDRP->IDTree = '.' . $ParentID . '.';
                $entMemberDRP->ParentID = $ParentID;
                $entMemberDRP->MasterID = 0;
                $entMemberDRP->DeleteMark = 1;
                $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
                $entMemberDRP->AddDate = date('Y-m-d H:i:s', time());
                $entMemberDRP->save();
                if ($entMemberDRP) { //修改DOP状态
                    DB::table('MemberDRP')->where('DRPID', $entMemberDRP->DRPID)->update(['IDTree' => $entMemberDRP->IDTree . $entMemberDRP->DRPID . '.']);
                }
                return redirect('/testpay/pay.html');
            }
            return redirect('/pay/pay.html');
        }
    }


    protected function checkMemberInfo($type, $name)
    {
        if ($type <= 0) {
            return '';
        }
        switch ($type) {
            case 1: $condition = [['UserName','=',$name]];   break;
            case 2: $condition = [['WeiXID','=',$name]];     break;
        }
        $entMemberInfo = EntMemberInfo::select('MemNumber', 'UserName', 'States', 'MemEndTime', 'WeiXID')
            ->where('DeleteMark', '1')
            ->where($condition)
            ->first();
        return $entMemberInfo;
    }


    public function pay()
    {
        $str            = $this->unifiedOrderXML();//返回统一下单所需的XML
        $prepay_id      = $this->postUnifiedOrder($str);//返回prepay_id
        $payArray       = $this->getPaySign($prepay_id);//支付所需参数
        $xmlOrder       = simplexml_load_string($str);
        $out_trade_no   = (string)$xmlOrder->out_trade_no;//订单
        //添加预支付记录
        $mopenid        = Session::get('openId');
        $memNumber      = $this->return_MemNumber();
        $entOrderPrepaidLog = new EntOrderPrepaidLog();
        $entOrderPrepaidLog->WeiXID = $mopenid;
        $entOrderPrepaidLog->OrderNumber = $out_trade_no;
        $entOrderPrepaidLog->MemNumber = $memNumber;
        $entOrderPrepaidLog->AddDate = date('Y-m-d H:i:s', time());
        $entOrderPrepaidLog->save();
        return view('pay.pay', compact('payArray', 'out_trade_no'));
    }




    public function paysuccess()
    {
        return view('pay.paysuccess');
    }


    public function mobiletest()
    {
        //$this->excel();
        //$nonceStr=str_random(20);//随机字符串
        $str = $this->unifiedOrderXML(); //$this->timeStamp();
        $prepay_id = $this->postUnifiedOrder($str);
        $payArray = $this->getPaySign($prepay_id);
        return view('mobiletest', ['str' => $prepay_id]);
    }

    /**获取prepay_id
     * @param $para  统一下单XML
     * @return \SimpleXMLElement[]|string
     */
    protected function postUnifiedOrder($para)
    {
        $prepay_id = '';
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $responseText = $this->getHttpResponsePOST($url, $para);
        if ($responseText != '') {
            $xmlUnifiedOrder = simplexml_load_string($responseText);
            $prepay_id = (string)$xmlUnifiedOrder->prepay_id;
        }
        return $prepay_id;
    }

    /**生成统一下单参数
     * @return string 返回XML
     */
    protected function unifiedOrderXML()
    {
        $MOpenid = Session::get('OPENID');
        $appid = env('WEIXIN_APPID');//公众账号ID
        $mch_id = '1407661602';//商户号

        $device_info = 'WEB';//设备号--否
        $nonce_str = str_random(20);//随机字符串
        $sign = '';//签名
        $body = '老侯代读会费';//商品描述
        //$detail = '';//商品详情 --否

        $attach = '老侯代读会费';//附加数据 --否
        $out_trade_no = 'cz' . date('YmdHis', time()) . $this->RandStr(3);//商户订单号
        $fee_type = 'CNY';//货币类型 --否
        $total_fee = '200000';//总金额200000
        $spbill_create_ip = $this->get_real_ip();//终端IP
        $time_start = date('YmdHis', time());//交易起始时间 --否yyyyMMddHHmmss
        //$time_expire = '';//交易结束时间 --否yyyyMMddHHmmss

        //$goods_tag = '';//商品标记 --否
        $notify_url = 'http://wx.laohoulundao.com/pay/wxnotifyurl';//通知地址
        $trade_type = 'JSAPI';//交易类型
        //$product_id = '';//商品ID --否
        //$limit_pay = '';//指定支付方式 --否
        $openid = $MOpenid;//用户标识 --否
        $orderXml = ['appid' => $appid, 'mch_id' => $mch_id, 'device_info' => $device_info, 'nonce_str' => $nonce_str, 'sign' => $sign, 'body' => $body, 'attach' => $attach, 'out_trade_no' => $out_trade_no, 'fee_type' => $fee_type, 'total_fee' => $total_fee, 'spbill_create_ip' => $spbill_create_ip, 'time_start' => $time_start, 'notify_url' => $notify_url, 'trade_type' => $trade_type, 'openid' => $openid];

        $orderXml['sign'] = $this->getSign($orderXml);
        //return strtoupper(md5($orderXmlSortStr));
        return $this->foreachXML($orderXml);
    }

    /** 拼接XML
     * @param $array 统一下单参数
     * @return string
     */
    protected function foreachXML($array)
    {
        $xml = '<xml>';
        if (count($array) > 0) {
            foreach ($array as $key => $val) {
                if ($val != '') {
                    $xml .= '<' . $key . '>' . $val . '</' . $key . '>';
                }
            }
        }
        return $xml . '</xml>';
    }

    /**生成签名
     * @param $array 统一下单参数
     * @return string--获取 prepay_id 签名
     */
    protected function getSign($array)
    {
        /**
         * 生成sign签名
         * 注：签名不能包含sign以及空的值
         */
        $orderXmlSortStr = '';
        $orderXmlSort = array_sort_recursive($array);

        foreach ($orderXmlSort as $key => $val) {
            if ($val != '' && $key != 'sign') {
                $orderXmlSortStr .= $key . '=' . $val . '&';
            }
        }
        return strtoupper(md5($orderXmlSortStr . 'key=' . env('WEIXIN_PAYKEY')));
    }

    /**生成支付数组
     * @param $prepay_id
     * @return string  返回 paySign 签名
     */
    protected function getPaySign($prepay_id)
    {
        $str = '';
        $appId = env('WEIXIN_APPID');
        $timeStamp = $this->timeStamp();
        $nonceStr = str_random(20);
        $package = 'prepay_id=' . $prepay_id;
        $signType = 'MD5';
        $paySign = '';
        $payArray = ['appId' => $appId, 'timeStamp' => $timeStamp, 'nonceStr' => $nonceStr, 'package' => $package, 'signType' => $signType, 'sign' => $paySign];
        $payArray['sign'] = $this->getSign($payArray);
        return $payArray;
    }

    /**时间戳
     * @return bool|string
     */
    protected function timeStamp()
    {
        return strtotime('now');
    }

    /**获取客户端IP
     * @return bool
     */
    protected function get_real_ip()
    {
        static $realip;
        if (isset($_SERVER)) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")) {
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }

    /**
     * 远程获取数据，GET模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * @param $cacert_url 指定当前工作目录绝对路径
     * return 远程输出的数据
     */
    protected function getHttpResponseGET($url)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL证书认证
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        //curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);
        return $responseText;
    }

    /**
     * 远程获取数据，POST模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * @param $cacert_url 指定当前工作目录绝对路径
     * @param $para 请求的数据
     * @param $input_charset 编码格式。默认值：空值
     * return 远程输出的数据
     */
    protected function getHttpResponsePOST($url, $para, $input_charset = '')
    {

        if (trim($input_charset) != '') {
            $url = $url . "_input_charset=" . $input_charset;
        }
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL证书认证
        //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        //curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_POST, true); // post传输数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $para);// post传输数据
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);

        return $responseText;
    }

    // 验证手机验证码
    public function addMobCode(Request $request)
    {
        $usermobile = $request->json('mobile');
        if (empty($usermobile)) {
            return 4;
        }
        $entMobileCodeTime = EntMobileCode::select('EndTime', 'ID')->where('Mobile', $usermobile)
            ->where('States', 1)
            ->orderBy('AddDate', 'desc')
            ->first();

        if (count($entMobileCodeTime) > 0) {
            $nowtime = date('Y-m-d h:i:s', time());
            $endtime = $entMobileCodeTime->EndTime;
            if (strtotime($nowtime) < strtotime($endtime)) {  // 时间没有到
                return 2;
            }
        }

        $mobileMessage  = new MobileMassege();
        $mobileMessage->mobile = $usermobile;
        $res = $mobileMessage->send_valid_code();
        $code = $res ? 3 : 4;
        return $code;
    }


    // 验证手机验证码
    public function checkMobCode(Request $request)
    {
        $result = '';
        $usermobcode = $request->json('mobcode');
        $usermobile = $request->json('mobile');

        if ($usermobcode == '6666') {
            return 3;
        }
        $messageModel = new MobileMassege();
        $res = $messageModel->check_valid_code($usermobile,$usermobcode);
        if($res){
            $result = 3;
            $messageModel->delete_code($usermobile,$usermobcode);
        }else{
            $result = 2;
        }
        return $result;
    }


    //随机数字
    protected function RandStr($n)
    {
        $s = '';
        $str = "123456789"; // 输出字符集
        $len = strlen($str) - 1;
        for ($i = 0; $i < $n; $i++) {
            $s .= $str[rand(0, $len)];
        }
        return $s;
    }

    /** 添加支付记录
     * @param Request $request
     * @return string 3-失败 1-成功
     */
    public function payOrderStore(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $order = $request->json('order');
                $MOpenid = Session::get('OPENID');
                $memNumber = $this->return_MemNumber();
                if ($MOpenid != '' && $order != '' && $memNumber != '') {
                    $entBookRenewLog = new EntBookRenewLog();
                    $entBookRenewLog->MemNumber = $memNumber;
                    $entBookRenewLog->OrderNumber = $order;
                    $entBookRenewLog->RenewDesc = '会员缴费';
                    $entBookRenewLog->WeiXID = $MOpenid;
                    $entBookRenewLog->AddDate = date('Y-m-d H:i:s', time());
                    $entBookRenewLog->save();
                    if ($entBookRenewLog) {
                        $upEntMemberInfo = EntMemberInfo::where('WeiXID', $MOpenid)->update(['States' => 1, 'RegisterType' => 2, 'MemEndTime' => date('Y-m-d H:i:s', strtotime("+1 year"))]);
                        EntOrderPrepaidLog::where('WeiXID', $MOpenid)->where('OrderNumber', $order)->delete();
                        $result = '1';
                    }
                } else {
                    if ($MOpenid != '') {
                        $upEntMemberInfo = EntMemberInfo::where('WeiXID', $MOpenid)->update(['States' => 1, 'RegisterType' => 2, 'MemEndTime' => date('Y-m-d H:i:s', strtotime("+1 year"))]);
                        $result = '1';
                    } else {
                        $result = '3';
                    }


                }
            }
        } catch (Exception $e) {
            $result = '3';
        }
        return $result;
    }

    protected function return_MemNumber()
    {
        $i = 0;
        try {
            $MName = Session::get('MName');
            $MKey = Session::get('MKey');
            if ($MName != '' && $MKey != '') {
                $entMemberInfo = EntMemberInfo::select('MemNumber')->where('UserName', $MName)->where('LoginKey', $MKey)
                    ->where('DeleteMark', '1')
                    ->first();
                if (count($entMemberInfo) > 0) {
                    $i = $entMemberInfo->MemNumber;
                }
            }
        } catch (ModelNotFoundException $e) {
            $i = 0;
        }
        return $i;
    }


    public function wxNotifyUrl()
    {
        $k = 0;
        $message = file_get_contents('php://input');
        $message = simplexml_load_string($message, 'SimpleXMLElement', LIBXML_NOCDATA);
        $appid = $message->appid;
        $resultcode = $message->result_code;
        $outtradeno = $message->out_trade_no;
        $openid = $message->openid;

        if ($appid == env('WEIXIN_APPID') && $resultcode == 'SUCCESS' && $openid != '' && $outtradeno != '') {
            $entMemberInfo = EntMemberInfo::select('MemNumber', 'States')->where('WeiXID', $openid)->where('DeleteMark', 1)->first();
            if (count($entMemberInfo) > 0) {
                if ($entMemberInfo->States == 0) {
                    DB::beginTransaction();
                    try {
                        $entBookRenewLog = new EntBookRenewLog();
                        $entBookRenewLog->MemNumber = $entMemberInfo->MemNumber;
                        $entBookRenewLog->OrderNumber = $outtradeno;
                        $entBookRenewLog->RenewDesc = '会员缴费';
                        $entBookRenewLog->WeiXID = $openid;
                        $entBookRenewLog->AddDate = date('Y-m-d H:i:s', time());
                        $entBookRenewLog->save();
                        EntMemberInfo::where('WeiXID', $openid)->update(['States' => 1, 'RegisterType' => 2, 'MemEndTime' => date('Y-m-d H:i:s', strtotime("+1 year"))]);
                        $this->pushMoneyLogStore($entMemberInfo->MemNumber);
                        $entReturnMsg = new EntReturnMsg();
                        $entReturnMsg->Msg = $appid . "-" . $message->mch_id . "-" . $resultcode . "-" . $outtradeno;
                        $entReturnMsg->TypeName = '支付描述';
                        $entReturnMsg->AddDate = date('Y-m-d H:i:s', time());
                        $entReturnMsg->save();
                        $k = 1;
                        DB::commit();
                    } catch (Exception $e) {
                        DB::rollBack();
                    }
                } else {

                    $k = 1;
                }
            }
        }
        if ($k == 1) {
            return $this->return_wxNotifyUrl();
        }
    }

    public function return_wxNotifyUrl()
    {
        $message = file_get_contents('php://input');
        $message = simplexml_load_string($message, 'SimpleXMLElement', LIBXML_NOCDATA);
        return View::make('payreturn.payreturn')->with('message', $message);
    }

    /**会员提点
     * @param string $memNumber
     */
    protected function pushMoneyLogStore($memNumber = '')
    {
        if ($memNumber != '') {
            $entMemberDRP = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID')->where('MemNumber', $memNumber)->first();
            if (count($entMemberDRP) > 0) {
                $parentID = $entMemberDRP->ParentID;
                if ($parentID > 0) {
                    $entMemberDRPTwo = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID', 'SalesMoney', 'FinishMoney', 'MemBalances', 'MemNumber', 'IsRebate')->where('DRPID', $parentID)->first();
                    if (count($entMemberDRPTwo) > 0) {
                        $parentIDTwo = $entMemberDRPTwo->ParentID;
                        if ($parentIDTwo == 0) {
                            //返点30%
                            DB::beginTransaction();
                            try {
                                $money = $this->scaleMoney * $this->scaleOne;//600
                                $toalMoney = $this->scaleMoney + $entMemberDRPTwo->FinishMoney;//2000+0
                                //会员余额
                                // $MemBalances=$entMemberDRPTwo->MemBalances+$toalMoney;
                                // DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney,'MemBalances'=>$MemBalances]);
                                $IsFinish = 0;
                                if ($toalMoney > $entMemberDRPTwo->SalesMoney) {
                                    $IsFinish = 1;
                                }
                                $entPushMoneyLog = new EntPushMoneyLog();
                                $entPushMoneyLog->MemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLog->Scale = $this->scaleOne;
                                $entPushMoneyLog->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLog->PayMoney = $money;
                                $entPushMoneyLog->MemberType = 1;
                                $entPushMoneyLog->IsFinish = $IsFinish;
                                $entPushMoneyLog->ToMemNumber = $memNumber;
                                $entPushMoneyLog->PushMoneyDesc = '发展新会员提点30%';
                                $entPushMoneyLog->DeleteMark = 1;
                                $entPushMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->save();
                                $k = 0;
                                if ($toalMoney >= $entMemberDRPTwo->SalesMoney) {
                                    if ($toalMoney == $entMemberDRPTwo->SalesMoney) {
                                        //返销售指标+销售业绩
                                        $k = 1;
                                    } else {
                                        if ($entMemberDRPTwo->FinishMoney > $entMemberDRPTwo->SalesMoney) {
                                            //提点+销售业绩
                                            $k = 2;
                                        } else {
                                            if ($entMemberDRPTwo->FinishMoney == $entMemberDRPTwo->SalesMoney) {
                                                $k = 2;
                                            } else {
                                                //提点+销售业绩
                                                $k = 3;
                                            }
                                        }

                                    }

                                } else {
                                    //销售业绩
                                    $k = 4;
                                }
                                switch ($k) {
                                    case 1:
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        }
                                        break;
                                    case 2:
                                        $memBalances = $money + $entMemberDRPTwo->MemBalances;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        break;
                                    case 3:
                                        $scaleMoneyTree = $toalMoney - $entMemberDRPTwo->SalesMoney;
                                        $moneyTree = $scaleMoneyTree * $this->scaleOne;
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        } else {
                                            $memBalances = $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        }
                                        break;
                                    case 4:
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney]);
                                        break;
                                }
                                DB::commit();
                            } catch (Exception $e) {
                                DB::rollBack();
                            }

                        } else {
                            $entMemberDRPTree = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID', 'IsRebate', 'SalesMoney', 'MemBalances', 'FinishMoney', 'MemNumber')->where('DRPID', $parentIDTwo)->first();
                            if (count($entMemberDRPTree)) {
                                //返点30%
                                $money = $this->scaleMoney * $this->scaleOne;
                                //已完成销售金额
                                $toalMoney = $this->scaleMoney + $entMemberDRPTwo->FinishMoney;
                                //会员余额
                                // $MemBalances=$entMemberDRPTwo->MemBalances+$toalMoney;
                                //  DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney,'MemBalances'=>$MemBalances]);
                                $IsFinish = 0;
                                if ($toalMoney > $entMemberDRPTwo->SalesMoney) {
                                    $IsFinish = 1;
                                }
                                $entPushMoneyLog = new EntPushMoneyLog();
                                $entPushMoneyLog->MemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLog->Scale = $this->scaleOne;
                                $entPushMoneyLog->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLog->PayMoney = $money;
                                $entPushMoneyLog->ToMemNumber = $memNumber;
                                $entPushMoneyLog->PushMoneyDesc = '发展新会员提点30%';
                                $entPushMoneyLog->MemberType = 1;
                                $entPushMoneyLog->IsFinish = $IsFinish;
                                $entPushMoneyLog->DeleteMark = 1;
                                $entPushMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->save();
                                $j = 0;
                                if ($toalMoney >= $entMemberDRPTwo->SalesMoney) {
                                    if ($toalMoney == $entMemberDRPTwo->SalesMoney) {
                                        //返销售指标+销售业绩
                                        $j = 1;
                                    } else {
                                        if ($entMemberDRPTwo->FinishMoney > $entMemberDRPTwo->SalesMoney) {
                                            //提点+销售业绩
                                            $j = 2;
                                        } else {
                                            if ($entMemberDRPTwo->FinishMoney == $entMemberDRPTwo->SalesMoney) {
                                                $j = 2;
                                            } else {
                                                //提点+销售业绩
                                                $j = 3;
                                            }
                                        }

                                    }

                                } else {
                                    //销售业绩
                                    $j = 4;
                                }
                                switch ($j) {
                                    case 1:
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        }
                                        break;
                                    case 2:
                                        $memBalances = $money + $entMemberDRPTwo->MemBalances;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        break;
                                    case 3:
                                        $scaleMoneyTree = $toalMoney - $entMemberDRPTwo->SalesMoney;
                                        $moneyTree = $scaleMoneyTree * $this->scaleOne;
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        } else {
                                            $memBalances = $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        }
                                        break;
                                    case 4:
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney]);
                                        break;
                                }
                                //返点5%
                                $moneyTwo = $this->scaleMoney * $this->scaleTwo;
                                //$toalMoneyTwo = $moneyTwo + $entMemberDRPTree->FinishMoney;
                                if ($entMemberDRPTree->FinishMoney >= $entMemberDRPTree->SalesMoney) {
                                    if ($entMemberDRPTree->IsRebate == 0) {
                                        $memBalances = $entMemberDRPTree->SalesMoney + $entMemberDRPTree->MemBalances + $moneyTwo;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['MemBalances' => $memBalances, 'IsRebate' => 1]);
                                    } else {
                                        $memBalances = $entMemberDRPTree->MemBalances + $moneyTwo;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['MemBalances' => $memBalances]);
                                    }
                                }
                                //已完成销售金额
                                //   $toalMoneyTwo = $moneyTwo + $entMemberDRPTree->FinishMoney;
                                //会员余额
                                // $MemBalancesTwo=$entMemberDRPTree->MemBalances+$moneyTwo;
                                //  DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['FinishMoney' => $toalMoneyTwo,'MemBalances' => $MemBalancesTwo]);
                                $IsFinishTwo = 0;
                                if ($entMemberDRPTree->IsRebate == 1) {
                                    $IsFinishTwo = 1;
                                }
                                $entPushMoneyLogTwo = new EntPushMoneyLog();
                                $entPushMoneyLogTwo->MemNumber = $entMemberDRPTree->MemNumber;
                                $entPushMoneyLogTwo->Scale = $this->scaleTwo;
                                $entPushMoneyLogTwo->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLogTwo->PayMoney = $moneyTwo;
                                $entPushMoneyLogTwo->IsFinish = $IsFinishTwo;
                                $entPushMoneyLogTwo->MemberType = 1;
                                $entPushMoneyLogTwo->ToMemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLogTwo->PushMoneyDesc = '下线合伙人发展新会员提点5%';
                                $entPushMoneyLogTwo->DeleteMark = 1;
                                $entPushMoneyLogTwo->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLogTwo->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLogTwo->save();
                            }
                        }
                    }
                }
            }
        }
    }
}